import {usePagination} from "@/composables/usePagination.js";
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import instance from "@/api/request.js";

export async function fetchPermissionList(params) {
    if (!params) {
        params = {
            name: '',
            type: null,
            status: null,
        }
    }
    return new Promise((resolve) => {
        try {
            instance.post("/permission/list", params).then((res) => {
                resolve(res.data);
            });
        } catch (error) {
            ElMessage.error("加载失败");
            console.log(error);
        }
    });
}

function useSysPermission() {
    // 查询参数
    const queryParams = reactive({
        name: '',
        type: null,
        status: null,
    });

    // 加载状态控制
    const loading = ref(false);

    // 查询分页参数
    const {current, total, size} = usePagination(10);


    // 表单查询结果
    const permissionList = ref([])

    const loadData = async () => {
        loading.value = true;
        try {
            permissionList.value = await fetchPermissionList({
                ...queryParams,
            });
        } catch (err) {
            ElMessage.error("加载失败");
        } finally {
            loading.value = false;
        }
    };

    const search = async () => {
        current.value = 1;
        await loadData();
    }

    const reset = async () => {
        queryParams.name = '';
        queryParams.type = null
        queryParams.status = null;
        await search();
    }

    const refresh = () => {

    }
    const handleCurrentChange = (newCurrent) => {
        current.value = newCurrent;
    }

    const handleSizeChange = (newSize) => {
        size.value = newSize;
    }

    return {
        queryParams,
        permissionList,
        current,
        total,
        size, loading,
        search,
        reset,
        refresh,
        handleCurrentChange,
        handleSizeChange,
    }
}

export default useSysPermission;